//
//  AppDelegate.m
//  SsehMaster
//
//  Created by 杨阳 on 2018/8/3.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "AppDelegate.h"
#import "LogInViewController.h"
#import "SsehHomePageViewController.h"
#import "SsehViewController.h"
#import "MBProgressHUD.h"

#import <UMCommon/UMCommon.h>
#import <UMCommonLog/UMCommonLogHeaders.h>
#import <JPUSHService.h>

#import "OrderDetailsViewController.h"
#import "OrderInforModel.h"

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

@interface AppDelegate ()<JPUSHRegisterDelegate>

@property (nonatomic,assign)NSInteger push_type;//推送类型

@property (nonatomic,assign)NSInteger order_id;//订单id

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self configUM];
    [self registerJPushWithOptions:launchOptions];
    if ([NSString userInfoEmpty]) {
        [self registApp];
    }else{
        [self toHomePage];
    }
    __weak typeof (self)weakSelf = self;
    [QYNetManager sharedManager].ErrorForTokenFailed = ^{
        [NSString removeUserInfo];
        [weakSelf errorLogin];
    };
    return YES;
}

-(void)configUM{
    
    [UMConfigure initWithAppkey:kSSEH_UM_APPKEY channel:nil];
    [UMCommonLogManager setUpUMCommonLogManager];
}

-(void)errorLogin{
    
    LogInViewController * regis = [[LogInViewController alloc]init];
    UINavigationController * nc = [[UINavigationController alloc]initWithRootViewController:regis];
    nc.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor]};
    nc.navigationBar.barTintColor = [UIColor appColor];
    self.window.rootViewController = nc;
    
}

//跳转登录界面
-(void)registApp{
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    LogInViewController * regis = [[LogInViewController alloc]init];
    UINavigationController * nc = [[UINavigationController alloc]initWithRootViewController:regis];
    nc.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor]};
    nc.navigationBar.barTintColor = [UIColor appColor];
    
    self.window.rootViewController = nc;
    [self.window makeKeyWindow];
}

//跳转首页
-(void)toHomePage{
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    SsehViewController * ssehtabBar = [[SsehViewController alloc]init];
    [self.window setRootViewController:ssehtabBar];
    [self.window makeKeyWindow];
    
}

- (void)registerJPushWithOptions:(NSDictionary *)launchOptions{
    // 3.0.0及以后版本注册
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    if (@available(iOS 12.0, *)) {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|UNAuthorizationOptionProvidesAppNotificationSettings;
    } else {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    }
    
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:launchOptions appKey:Jpush_AppKey
                          channel:nil
                 apsForProduction:Jpush_IsProduction
            advertisingIdentifier:nil];
    
    //获取Token、也即registrationID
    //NSString *token = DEF_PERSISTENT_GET_OBJECT(Jpush_TOKEN);
    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            DLog(@"Jpush_Token>>>>>>%@",registrationID);
            DEF_PERSISTENT_SET_OBJECT(registrationID, Jpush_TOKEN);
        }else{
            DLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkDidReceiveMessage:)
                                                 name:kJPFNetworkDidReceiveMessageNotification
                                               object:nil];
}

- (void)showErrorTipWithTitle:(NSString*)title {
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.window animated:YES];
    hud.mode = MBProgressHUDModeCustomView;
    hud.label.text = title;
    hud.contentColor = [UIColor whiteColor];
    hud.customView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"closeNet"]];
    hud.bezelView.backgroundColor = [UIColor blackColor];
    [self.window addSubview:hud];
    [hud showAnimated:YES];
    [hud hideAnimated:YES afterDelay:1.0f];
}


// 接收到通知事件
- (void)networkDidReceiveMessage:(NSNotification *)notification {
   
    NSDictionary *userInfo = [notification userInfo];
    NSString *msg = [userInfo valueForKey:@"content"];
    NSDictionary *valueDict = [self hsDictionaryWithJSON:[userInfo objectForKey:@"value"]];
    if ([valueDict isKindOfClass:[NSDictionary class]]) {
        self.push_type = [[valueDict objectForKey:@"type"] integerValue];
        if (self.push_type) {
            self.order_id = [[valueDict objectForKey:@"order_id"] integerValue];
            if ([NSString userInfoEmpty]) {
                [self registApp];
            }else{
                if (self.order_id) {
                    [self doPush:userInfo];
                }else{
                    SHOW_ALERT(@"消息通知",msg,@"确定",nil,0);
                }
            }
        }else{
            SHOW_ALERT(@"消息通知",msg,@"确定",nil,0);
        }
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    //取消通知
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - JPUSHRegisterDelegate
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    DLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    // Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    DLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    if (@available(iOS 12.0, *)) {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|UNAuthorizationOptionProvidesAppNotificationSettings;
    } else {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    }
    
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
   
    NSString *msg = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];
    NSDictionary *valueDict = [self hsDictionaryWithJSON:[userInfo objectForKey:@"value"]];
    if ([valueDict isKindOfClass:[NSDictionary class]]) {
        self.push_type = [[valueDict objectForKey:@"type"] integerValue];
        if (self.push_type) {
            self.order_id = [[valueDict objectForKey:@"order_id"] integerValue];
            if (application.applicationState != UIApplicationStateActive) {
                if ([NSString userInfoEmpty]) {
                    [self registApp];
                }else{
                    if (self.order_id) {
                        [self doPush:userInfo];
                    }else{
                        SHOW_ALERT(@"消息通知",msg,@"确定",nil,0);
                    }
                }
            }else{
                if ([NSString userInfoEmpty]) {
                    [self registApp];
                }else{
                    [self doPush:userInfo];
                }
            }
        }else{
            SHOW_ALERT(@"消息通知",msg,@"确定",nil,0);
        }
    }
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {

}

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        DLog(@"iOS10 前台收到远程通知:%@",userInfo);
        NSString *msg = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];
        NSDictionary *valueDict = [self hsDictionaryWithJSON:[userInfo objectForKey:@"value"]];
        if ([valueDict isKindOfClass:[NSDictionary class]]) {
            self.push_type = [[valueDict objectForKey:@"type"] integerValue];
            if (self.push_type) {
                self.order_id = [[valueDict objectForKey:@"order_id"] integerValue];
                if ([NSString userInfoEmpty]) {
                    [self registApp];
                }else{
                    if (self.order_id) {
                        SHOW_ALERT(@"消息通知",msg,@"取消",@"查看",0);
                    }else{
                         SHOW_ALERT(@"消息通知",msg,@"确定",nil,0);
                    }
                }
            }else{
                SHOW_ALERT(@"消息通知",msg,@"确定",nil,0);
            }
        }
    }
}


- (NSDictionary *)hsDictionaryWithJSON:(id)json {
    if (!json || json == (id)kCFNull) return nil;
    NSDictionary *dic = nil;
    NSData *jsonData = nil;
    if ([json isKindOfClass:[NSDictionary class]]) {
        dic = json;
    } else if ([json isKindOfClass:[NSString class]]) {
        jsonData = [(NSString *)json dataUsingEncoding : NSUTF8StringEncoding];
    } else if ([json isKindOfClass:[NSData class]]) {
        jsonData = json;
    }
    if (jsonData) {
        dic = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:NULL];
        if (![dic isKindOfClass:[NSDictionary class]]) dic = nil;
    }
    return dic;
}


- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    completionHandler();
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        completionHandler(UIBackgroundFetchResultNewData);
        NSString *msg = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];
        
        NSDictionary *valueDict = [self hsDictionaryWithJSON:[userInfo objectForKey:@"value"] ];
        if ([valueDict isKindOfClass:[NSDictionary class]]) {
            self.push_type = [[valueDict objectForKey:@"type"] integerValue];
            self.order_id = [[valueDict objectForKey:@"order_id"] integerValue];
            if ([NSString userInfoEmpty]) {
                [self registApp];
            }else{
                if (self.order_id) {
                    [self doPush:userInfo];
                }else{
                    SHOW_ALERT(@"消息通知",msg,@"确定",nil,0);
                }
            }
        }
    }
}
#endif

#ifdef __IPHONE_12_0
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{
    NSString *title = nil;
    if (notification) {
        title = @"从通知界面直接进入应用";
    }else{
        title = @"从系统设置界面进入应用";
    }
    UIAlertView *test = [[UIAlertView alloc] initWithTitle:title
                                                   message:@"pushSetting"
                                                  delegate:self
                                         cancelButtonTitle:@"yes"
                                         otherButtonTitles:nil, nil];
    [test show];
    
}
#endif

// log NSSet with UTF8
// if not ,log will be \Uxxx
- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}
#pragma mark - 推送处理
- (void)doPush:(NSDictionary *)userInfo{
    //界面跳转
    if (self.push_type&&self.order_id) {
        OrderDetailsViewController *detailVC = [[OrderDetailsViewController alloc]init];
        OrderDetail *model = [[OrderDetail alloc]init];
        model.order_id = [NSString stringWithFormat:@"%ld",(long)self.order_id];
        detailVC.orderModel = model;
        if ([self.window.rootViewController isKindOfClass:[SsehViewController class]]) {
            SsehViewController* tabController = (SsehViewController*)self.window.rootViewController;
            UINavigationController* navController = tabController.selectedViewController;
            dispatch_time_t delayTime = 0;
            if (!navController) {
                delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC));
            }
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                [navController pushViewController:detailVC animated:YES];
            });
        }
    }
}
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ((buttonIndex == 1 || alertView.tag == 188 ) && self.order_id) {
        OrderDetailsViewController *detailVC = [[OrderDetailsViewController alloc]init];
        OrderDetail *model = [[OrderDetail alloc]init];
        model.order_id = [NSString stringWithFormat:@"%ld",(long)self.order_id];
        detailVC.orderModel = model;
        if ([self.window.rootViewController isKindOfClass:[SsehViewController class]]) {
            SsehViewController* tabController = (SsehViewController*)self.window.rootViewController;
            UINavigationController* navController = tabController.selectedViewController;
            dispatch_time_t delayTime = 0;
            if (!navController) {
                delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC));
            }
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                [navController pushViewController:detailVC animated:YES];
            });
        }
    }
}

@end
